import { parse } from "semver"

const REGISTER = 'REGSITER'
const SIGN_IN = 'SIGN_IN'
const SIGN_OUT = 'SIGN_OUT'

export default {
  mutations: {
    [REGISTER](state, user) {
      let userExists = false
      for(let i=0;i<localStorage.length;i++) {
        // 判断是否为用户
        if(localStorage.key(i).indexOf('user') != -1) {
          // 如果为用户，则判断用户名是否已存在
          if(JSON.parse(localStorage.getItem(localStorage.key(i))).user == user.user) {
            userExists = true
            break;
          }
        }
      }

      // 如果用户名不存在，则存储用户
      if(!userExists) {
        localStorage.setItem('user'+ localStorage.length, JSON.stringify(user))
        sessionStorage.register = 1 //注册成功
      } else {
        sessionStorage.register = 0 //注册失败
      }
    },
    [SIGN_IN](state, user) {
      let localuser = '', findUser = false, key = ''
      // 在本地存储中寻找是否存在此用户
      for(let i=0;i<localStorage.length;i++) {
        // 判断是否为用户
        if(localStorage.key(i).indexOf('user') != -1) {
          // 寻找相同用户名
          if(JSON.parse(localStorage.getItem(localStorage.key(i))).user == user.name) {
            localuser = JSON.parse(localStorage.getItem(localStorage.key(i)))
            findUser = true
            key = localStorage.key(i)
            break;
          }
        }
      }
      
      // 用户密码符合
      if(findUser && localuser.pwd == user.pwd) {
        sessionStorage.login = 1 //登录成功状态
        sessionStorage.user = JSON.stringify(localuser)
        sessionStorage.userId = key
      } else {
        sessionStorage.login = 0 //登录失败状态
      }
    },
    [SIGN_OUT](state) {
      sessionStorage.register = 0
      sessionStorage.login = 0
    }
  },
  actions: {
    register({commit}, user) {
      commit(REGISTER, user)
    },
    signIn({commit}, user) {
      commit(SIGN_IN, user)
    },
    signOut({commit}) {
      commit(SIGN_OUT)
    }
  }
}